#!/bin/bash

echo '******批量自动同步密钥脚本******:'


#同步密钥目标机
target_ip_file=$@
if [[ $* = '' ]]; then
	echo -e "\033[31m 请至少选择一个目标ip配置文件!!! \033[0m"
    exit
fi

#判断文件是否存在
for target_ip_file in "$@"; do
	if [ ! -e $target_ip_file ]; then
		echo -e "\033[31m ${target_ip_file}配置文件不存在!!! \033[0m"
    	exit
	fi
done		



#同步密钥脚本
for target_ip_file in "$@"; do

	while read line;do
		ip=`echo $line | cut -d " " -f1`
	    username=`echo $line | cut -d " " -f2`
	    password=`echo $line | cut -d " " -f3`

	    expect <<EOF
	        spawn ssh-copy-id -i /root/.ssh/id_rsa.pub ${username}@${ip}
	        expect {
	            "continue connecting" {send "yes\r";exp_continue}
	            "password" {send "${password}\r"}
	        }
	        expect eof
EOF
	done < $target_ip_file

done



echo -e "\033[32m ******同步秘钥执行成功****** \033[0m"